import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginApi, registerApi, getUserInfoApi } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = ref(null)
  // 登录状态
  const isLoggedIn = ref(false)
  // 记住我状态
  const rememberMe = ref(false)

  // 用户登录
  const login = async (credentials) => {
    try {
      const res = await loginApi(credentials)
      
      // 保存用户token
      uni.setStorageSync('token', res.token)
      
      // 获取用户信息
      await getUserInfo()
      
      // 更新登录状态
      isLoggedIn.value = true
      
      // 记住用户名密码
      if (rememberMe.value) {
        uni.setStorageSync('rememberedCredentials', {
          username: credentials.username,
          password: credentials.password
        })
      } else {
        uni.removeStorageSync('rememberedCredentials')
      }
      
      return true
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  // 用户注册
  const register = async (userData) => {
    try {
      await registerApi(userData)
      return true
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const res = await getUserInfoApi()
      userInfo.value = res
      return res
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  // 用户登出
  const logout = () => {
    uni.removeStorageSync('token')
    userInfo.value = null
    isLoggedIn.value = false
  }

  // 初始化用户状态
  const initUserState = () => {
    const token = uni.getStorageSync('token')
    if (token) {
      isLoggedIn.value = true
      getUserInfo()
    }
    
    // 初始化记住我状态
    const remembered = uni.getStorageSync('rememberedCredentials')
    if (remembered) {
      rememberMe.value = true
    }
  }

  return {
    userInfo,
    isLoggedIn,
    rememberMe,
    login,
    register,
    getUserInfo,
    logout,
    initUserState
  }
})